<template>
	<div class="page-index">
		<h3 class="p-title">章节目录</h3>
		<div id="mynetwork" ref="mynetwork" class="p-body"></div>
		<div class="btn-panel">
			<el-button  v-if="chapterData.length==0" type="primary" @click="addChapter(head_addr)">攥写章节</el-button>
			<el-button  v-if="isCurrentNode" size="small" type="primary" @click="addChapter()">续写章节</el-button>
			<el-button  v-if="isCurrentNode" size="small" type="primary" @click="readChapter()">阅读本章</el-button>
			<el-button  v-if="isCurrentNode" size="small" type="primary" @click="addBook()">阅读本分支</el-button>
		</div>
	</div>
</template>

<script>
import * as web3CTR from '@/utils/web3-ctr'
import vis from 'vis'
import _ from 'lodash'
const uuidv1 = require('uuid/v1');

function translateData(_nodes){
	let edges = []
	let nodes = []
	let node_map = {}
	_nodes.forEach(ele => {
		let type = web3CTR.web3.utils.hexToNumberString(ele.type)
		let shape = 'text'
		switch(type){
			case '0':
				shape='circle'
				break;
			case '1':
				shape='ellipse'
				break;
			case '2':
				shape='box'
				break;
		}
		edges.push({
			to: ele.addr,
			from: ele.prev,
			arrows: 'to',
		})
		let node_tem = {
			id: ele.addr,
			label: ele.text,
			data: ele,
			level: web3CTR.web3.utils.hexToNumberString(ele.level._hex)*1
		}
		nodes.push({
			id: ele.addr,
			label: ele.text,
			data: ele,
			level: web3CTR.web3.utils.hexToNumberString(ele.level._hex)*1
		})
		node_map[ele.addr] = ele
	});

	return {
		top_data:{
			edges,
			nodes,
			arrows: 'to'
		},
		node_map
	}
}
function leaf(nodes,edges){
	let leaf_list = []
	nodes.forEach(ele => {
		if(JSON.stringify(edges).indexOf(ele.addr)!=-1){
			leaf_list.push({
				addr: ele.addr,
				prev: ele.prev,
				title: ele.title
			})
		}
	})
	return leaf_list
}
export default {
	name: 'story-list',
	data(){
		return{
			chapterData:[],
			head_addr: '',// head address
			top_data:{
				edges:[],
				nodes:[]
			},
			node_map: {},
			leaf: [],
			network: {},
			isCurrentNode: false,
			currentNode: {}
		}
	},
	created(){
		this.head_addr = this.$route.params['headaddr']
		this.getChapterIndex(this.head_addr)
		
	},
	mounted(){
		let ctn = this.$refs.mynetwork
		var options = {
			edges: {
				smooth: {
					// type: 'cubicBezier',
				}
			},
			layout: {
				hierarchical: {
					direction: "UD"
				}
			},
		};
		var container = document.getElementById('mynetwork');
		
		window.network = new vis.Network(container,{ edges:[], nodes:[] }, options);
	},
	watch:{
		currentNode(val){
			this.isCurrentNode = !_.isEmpty(val)
			console.log(this.isCurrentNode,"watch")
		}
	},
	methods:{
		//阅读章节
		readChapter(){
			this.$router.push({
				name:'chapter-detail',
				params: {
					addr: this.currentNode.addr
				}
			})
		},
		// h_addr: 本小说的head合约地址
		getChapterIndex(h_addr){
			console.log("h_addr-^-->", h_addr)
			web3CTR.getChapterIndex(h_addr).then((indexData)=>{
				this.chapterData = indexData
				let {top_data, node_map} = translateData(indexData)
				this.leaf = leaf(indexData, top_data.edges)
				console.log("leaf===>", this.leaf)
				Object.assign(this.top_data, top_data)
				Object.assign(this.node_map, node_map)
				this.rend_top(this.top_data)
				console.log("indexData-@->", indexData)
			})
		},
		addChapter(head_addr){
			this.$router.push({
				name:'add-chapter',
				params:{
					prev: this.chapterData.length==0 ? head_addr: this.currentNode.addr
				},
				query: {
					headaddr: this.head_addr,
					level: this.chapterData.length==0 ? 1 : parseInt(this.currentNode.level) + 1
				}
			})
		},
		rend_top(){
			let _this = this
			var container = document.getElementById('mynetwork');

			window.network.setData(this.top_data)

			window.network.on("click", function ({edges,event,nodes,pointer}) {
				
				//------------------->>>>>>
				// let nodeId = this.getNodeAt(pointer.DOM)
				
				// let node = _.get(_this.node_map, nodeId, null)
				
				// if(node){
				// 	if(_.get(node, 'data.type', "chapter")=='addBtn'){
				// 		console.log("addBtn", node)
				// 		_this.$router.push({
				// 			name:'add',
				// 			params:{prev: node.data.prev},
				// 			query: {
				// 				headaddr: _this.head_addr,
				// 				level: parseInt(node.level)
				// 			}
				// 		})

				// 	}else{
				// 		_this.currentNode = node
				// 		_this.showAddBtn()
				// 		_this.addButton(node)
				// 		window.network.setData(_this.top_data)
				// 		let len_nodes = _this.top_data.nodes.length
				// 		let len_edges = _this.top_data.edges.length
				// 		_this.delBtnDelay(len_nodes-1, len_edges-1)
				// 	}
				// }
				//-------------------<<<<<<<
				
			});
			window.network.on("select", function ({edges,event,nodes,pointer}) {
				let nodeId = this.getNodeAt(pointer.DOM)
				
				let node = _.get(_this.node_map, nodeId, null)
				console.log("selected", node)
				_this.currentNode = node
			});
		},
		/**延迟删除按钮
		 * 
		 */
		delBtnDelay(index_nodes, index_edges){
			setTimeout(()=>{
				this.top_data.nodes.splice(index_nodes, 1)
				this.top_data.edges.splice(index_edges, 1)
				window.network.setData(this.top_data)
			},2000)
		},
		networkRender(data){
			this.showButton(this.leaf)
		},
		/** 
		 * 显示攥写按钮
		 */
		addButton(node){
			let btn = {
				label: '续写章节',
				id: uuidv1(),
				data: _.merge({},node.data, {type:'addBtn', prev: node.addr}),
				level: parseInt(node.level) +1,
				color: "#7be140"
			}
			let edge = {
				from:node.addr,
				to: btn.id,
				arrows: 'to'
			}
			this.top_data.nodes.push(btn)
			this.top_data.edges.push(edge)
			this.node_map[btn.id]=btn

			console.log("top_data********", this.top_data)
		},
		showAddBtn(){
			this.isCurrentNode = true
			console.log("currentNode---->", this.currentNode)
		}
	}
}
</script>
<style lang="stylus" scoped>
.page-index{
	display: flex;
	flex-direction : column;
	height: 100%;
	.p-title{
		
	}
	.p-body{
		flex: 1
	}
	.btn-panel{
		height: 100px;
	}
}
</style>
